import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { Product, ProductFormData } from '../models/product.model';

@Injectable({
  providedIn: 'root'
})
export class ProductService {
  private products = new BehaviorSubject<Product[]>([]);
  public products$ = this.products.asObservable();
  private nextId = 1;

  constructor() {
    // Initialize with some mock data
    const mockProducts: Product[] = [
      {
        id: this.nextId++,
        name: 'iPhone 15 Pro',
        category: '电子产品',
        price: 7999,
        stock: 50,
        description: '最新款苹果手机，搭载A17 Pro芯片',
        status: 'active',
        createdAt: new Date('2024-01-15')
      },
      {
        id: this.nextId++,
        name: 'MacBook Pro 14',
        category: '电子产品',
        price: 14999,
        stock: 30,
        description: 'M3芯片，专业级笔记本电脑',
        status: 'active',
        createdAt: new Date('2024-02-20')
      },
      {
        id: this.nextId++,
        name: 'AirPods Pro 2',
        category: '配件',
        price: 1899,
        stock: 100,
        description: '主动降噪无线耳机',
        status: 'active',
        createdAt: new Date('2024-03-10')
      },
      {
        id: this.nextId++,
        name: 'iPad Air',
        category: '电子产品',
        price: 4799,
        stock: 0,
        description: 'M1芯片平板电脑',
        status: 'inactive',
        createdAt: new Date('2024-04-05')
      },
      {
        id: this.nextId++,
        name: 'Apple Watch Series 9',
        category: '配件',
        price: 3199,
        stock: 75,
        description: '智能手表，健康监测',
        status: 'active',
        createdAt: new Date('2024-05-12')
      }
    ];
    this.products.next(mockProducts);
  }

  getProducts(): Observable<Product[]> {
    return this.products$;
  }

  addProduct(productData: ProductFormData): void {
    const currentProducts = this.products.value;
    const newProduct: Product = {
      id: this.nextId++,
      ...productData,
      createdAt: new Date()
    };
    this.products.next([...currentProducts, newProduct]);
  }

  updateProduct(id: number, productData: ProductFormData): void {
    const currentProducts = this.products.value;
    const index = currentProducts.findIndex(p => p.id === id);
    if (index !== -1) {
      currentProducts[index] = {
        ...currentProducts[index],
        ...productData
      };
      this.products.next([...currentProducts]);
    }
  }

  deleteProduct(id: number): void {
    const currentProducts = this.products.value;
    this.products.next(currentProducts.filter(p => p.id !== id));
  }

  getProductById(id: number): Product | undefined {
    return this.products.value.find(p => p.id === id);
  }
}
